# -*-coding:utf-8 -*-
#
# Created on 2019/5/13, by felix
#

from rest_framework.decorators import action, list_route, detail_route  # list_router和detail_router都是调用这个
from base.views import BaseViewSet

from .models import CommandInfo, Owner
from .serializers import CommandInfoSerializer, CommandInfoCreateSerializer, OwnerSerializer, OwnerCreateSerializer
from .filters import CommandInfoFilter


# 100 基本的增删改查
class CommandInfoViewSet(BaseViewSet):
    """command 列表"""

    queryset = CommandInfo.objects.filter(is_deleted=False).order_by('-id')  # queryset，可过滤
    filter_class = CommandInfoFilter  # 模糊匹配，精确匹配
    http_method_names = ['get', 'post', 'put', 'delete']  # 限制方法

    # 方法1
    # serializer_class = CommandInfoSerializer  # 序列化器or验证器

    # 方法2
    def get_serializer_class(self):  # 根据方法不同用不同serializer
        print(self.action)
        if self.action in ['create']:
            return CommandInfoCreateSerializer
        if self.action in ['list']:
            return CommandInfoSerializer

    @action(methods=['get'], detail=False, url_path='list')
    def get_list(self, request, *args, **kwargs):
        print(kwargs)  # {'pk': '23'}
        return self.render_to_json_response(data='/foreignkey/v1/command/info/list')

    @action(methods=['get'], detail=True, url_path='detail')
    def get_detail(self, request, *args, **kwargs):
        print(kwargs)  # {'pk': '23'}
        return self.render_to_json_response(data='/foreignkey/v1/command/info/%s/detail' % kwargs.get('pk'))

    """
    110 action装饰器
        函数名称不能重复
            def get_list
            def get_detail
        detail
            False 对应的是/foreignkey/v1/command/info/list
            True 对应的是/foreignkey/v1/command/info/%s/detail' % kwargs.get('pk')
                        /foreignkey/v1/command/info/1/detail'

        @action(methods=['get'], detail=False, url_path='list')
            methods 大小写随意
            detail必须有
            ulr_path 为url
            url_name 为url对应的name，类似于base-name
    """


class CommandOwnerViewSet(BaseViewSet):
    queryset = Owner.objects.filter(is_deleted=False).order_by('-id')

    # 根据方法不同用不同serializer
    # serializer_class = OwnerSerializer
    def get_serializer_class(self):
        print(self.action)
        if self.action in ['list', 'retrieve']:
            return OwnerSerializer
        if self.action in ['create']:
            return OwnerCreateSerializer

    def list(self, request, *args, **kwargs):
        # queryset不能直接返回给前台数据
        queryset = self.filter_queryset(self.get_queryset())
        print(type(queryset))

        # 序列化全部数据
        serializer = self.get_serializer(queryset, many=True)  # OwnerSerializer  序列化器+自定义序列化字段
        return self.render_to_json_response(data=serializer.data)

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return self.render_to_json_response(data=serializer.data)

    # 重写create方法
    def create(self, request, *args, **kwargs):
        # 数据类型合法，但数据内容不一定合法，需要校验数据，校验（参与反序列化)的数据需要赋值给data
        serializer = OwnerCreateSerializer(data=request.data)  # OwnerCreateSerializer 反序列化+验证器

        # 反序列化对象调用is_valid()完成检验，校验失败的失败信息都会被存储在  序列化对象.errors
        serializer.is_valid(raise_exception=True)

        # 校验通过，完成新增
        owner_obj = self.perform_create(serializer)  # 实质是save方法
        # owner_obj = serializer.save()

        # 重新序列化，输出结果
        serializer = OwnerSerializer(owner_obj)
        return self.render_to_json_response(data=serializer.data)

    def perform_create(self, serializer):
        obj = serializer.save()
        return obj  # 返回obj对象实例，需要序列化返回
